package com.zyg.proxy.base;

import com.zyg.proxy.service.UserService;
import com.zyg.proxy.service.impl.UserServiceImpl;
import javassist.util.proxy.Proxy;
import javassist.util.proxy.ProxyFactory;


/**
 * Javassist动态代理
 */
public class JavassistDemo {
    public static void main(String[] args) {
        UserService userServiceJavassistProxy = createUserServiceJavassistProxy(UserServiceImpl.class);
        userServiceJavassistProxy.save();
    }

    public static UserService createUserServiceJavassistProxy(Class clazz) {
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setSuperclass(clazz);
        // 设置拦截目标
        proxyFactory.setFilter((m) -> m.getName().equals("save"));
//        proxyFactory.setHandler(((self, method, proceed, args) -> {
//            System.out.println(method.getName());
//            Object object = proceed.invoke(self, args);
//            if (method.getName().equals("save")) {
//                System.out.println("刮大白3");
//                System.out.println("贴墙纸3");
//            }
//            //执行原始方法
//            return object;
//        }));
        Class aClass = proxyFactory.createClass();
        UserService proxy = null;
        try {
            proxy = (UserService)aClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        ((Proxy)proxy).setHandler((self, method, proceed, args) -> {
            System.out.println("刮大白3");
            System.out.println("贴墙纸3");
            //执行原始方法
            Object object = proceed.invoke(self, args);
            return object;
        });
        System.out.println(proxy.getClass());
        return proxy;
    }

}
